#!/usr/bin/php
<?php
//error_reporting(E_ERROR | E_PARSE);

echo "\nCreating a new file that contains all the area id's associated with STY (story) areas.\n";

// Create a file to house the story areas
$filename = "/sv/customer/apnnz/conf/styareas.new";
echo "\nStory Areas File is: ".$filename."\n";

$link = mysql_connect('10.160.190.128', 'aimatch', 'RMSAdmin');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('apnnz')) {
    die('Could not select database: ' . mysql_error());
}
$result = mysql_query('select id from areas where name like "%.STY" order by id');
if (!$result) {
    die('Could not query:' . mysql_error());
}

$rows=mysql_num_rows($result);

if (!$handle = fopen($filename, 'w+')) {
    echo "\nCannot open file: ".$filename."\n";
    exit;
}
$i=0;
while($i < $rows) {
	$lines = mysql_result($result, $i, 0);
	if(fwrite($handle,$lines."\n") === FALSE) {
		echo "\nCannot write to file: ".$filename."\n";
		exit;
	}
	$i++; 
}

mysql_close($link);
fclose($handle);


if(file_exists($filename)) {
	echo "\nValidating file: ".$filename."\n";
	$file_size = filesize($filename);
	if($file_size < 17200) {
		echo "\nFAILURE!!! The file doesn't appear to contain enough data. The file size is: ".$file_size."\n";
		echo "\nRemoving the file.\n";
		unlink($filename);
	}
	else {
		echo "\nSUCCESS!!! The file appears to be the proper size. The file size is: ".$file_size."\n";

		// Since the file appears to be valid, move the final sipped file to shared data
		echo "\nMOVE THE FILE TO SHARED VOLUME\n";
		$move_cmd = "mv ".$filename." /sv/customer/apnnz/conf/styareas.txt";
		echo $move_cmd."\n";
		shell_exec($move_cmd);
	}
}
else {
	echo "\nFAILURE!!! The file doesn't exist. The file is supposed to be: ".$filename."\n";
}




?>